<?php

namespace adapters;

class DbSimple extends \adapters\db
{
	protected $usesPlaceholders = true;
	protected $phValue = "?";
	protected $phTable = "?#";

	public function __construct($config)
	{
		if (empty($config))
		{
			die("Valid config required");
		}

		if (!defined("PATH_SEPARATOR"))
		{
			define("PATH_SEPARATOR", getenv("COMSPEC")? ";" : ":");
		}

		core("File")->ImportScript(_SERVICES_DIR."db/DbSimple/Generic.php");

		$dsn = "mysql://".$config['dbuser'].":".$config['dbpass']."@".$config['dbhost']."/".$config['dbname'];

		$db = @\DbSimple_Generic::connect($dsn);

		if (!$db->link)
		{
			service("debug")->Error("Couldn't connect to database");
		}

		$this->SetLib($db);

		$db->setErrorHandler(array($this, "Error"));
		//$db->SetLogger(array($this, "Log"));

		$db->query("SET NAMES utf8");
		$db->query("SELECT now()");
		//$db->query("SET AUTOCOMMIT=0;");
	}

	protected function DoSelect()
	{
		$sql = $this->GetSql();
		$args = $this->placeholders;

		array_unshift($args, $sql);

		switch ($this->fetch)
		{
			case "column":
				$method = "SelectCol";
				break;

			case "row":
				$method = "SelectRow";
				break;

			case "cell":
				$method = "SelectCell";
				break;

			default:
				$method = "Select";
				break;
		}

		return call_user_func_array(array($this->lib, $method), $args);
	}

	protected function DoUpdate()
	{

	}

	protected function DoDelete()
	{

	}

	protected function DoQuery()
	{

	}

	public function Error($db, $error)
	{
		$errorQuery = preg_match("~'(.*)'~i", $error['message'], $found);
		@$errorQuery = $found[1];

		$query = $error['query'];

		preg_match("~(.*) line ([0-9]+)~i", $error['context'], $backtrace);

		$file = basename($backtrace[1]);

		$line = $backtrace[2];

		//$res = str_replace($errorQuery, "<span style='color:red;font-size:larger;'><strong>&rarr;</strong></span>$errorQuery", $query);
		$res = str_replace($errorQuery, " → $errorQuery", $query);

		if ($query == $res)
		{
			$res = explode(" at", $db);
			$res = $res[0];
		}

		service("debug")->Error("SQL error: " . $res);

		return true;
	}
}